package com.summer.Filter;

import com.alibaba.fastjson.JSON;
import com.summer.common.OperateThreadLocal;
import com.summer.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class EmployeeLoginFilter implements Filter {
    // TODO 用于路径匹配，方法match（pattern，path）， 第一个参数为匹配规则，第二个才是我们需要匹配的路径
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestUri = request.getRequestURI();

        log.info("过滤器启动成功，当前请求路径："+ requestUri + "\n正在判断是否需要拦截此路径...");
        //1. 判断哪些路径不需要拦截，存入字符串 TODO 静态页面可以不用拦截，controller中的请求路径才需要拦截
        String[] excludePath = new String[]{"/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"};

        //2. 判断请求路径是否需要拦截，若不需要拦截则放行
        if (matchPath(excludePath, requestUri)){
            log.info("当前请求路径："+ requestUri + "不需要拦截，已放行！");
            filterChain.doFilter(request, response);
            return;
        }

        log.info("请求路径："+ requestUri + "需要拦截，判断是否已登录...！");
        //3. 判断用户是否登录，若若已登录则放行
        if (request.getSession().getAttribute("employee") != null){
            log.info("用户已登录！，放行！");
            long id = (long) request.getSession().getAttribute("employee");
            // 向当前请求线程存入id数据
            log.info("已将登入用户id:" + id + " 存入ThreadLocal");
            OperateThreadLocal.setLocalThreadAttribute(id);
            filterChain.doFilter(request,response);
            return;
        }

        if (request.getSession().getAttribute("user") != null){
            log.info("用户已登录！，放行！");
            long id = (long) request.getSession().getAttribute("user");
            // 向当前请求线程存入id数据
            log.info("已将登入用户id:" + id + " 存入ThreadLocal");
            OperateThreadLocal.setLocalThreadAttribute(id);
            filterChain.doFilter(request,response);
            return;
        }

        //4. 未登录则向前端返回未登录的json数据
        log.info("用户未登录！，跳转登录页...");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));


    }

    /**
     * 判断路径匹配方法
     * @param paths 匹配规则
     * @param requestPath 要匹配的路径
     * @return 若匹配成功则返回ture
     */
    public boolean matchPath(String[] paths, String requestPath){
        if(requestPath.equals("/front/images/headPage2.png")){
            return false;
        }
        for (String path : paths) { // 访问移动端头像不放行
            if(ANT_PATH_MATCHER.match(path, requestPath)){
                return true;
            }
        }
        return false;
    }

}
